/*
* Copyright 2010 ANDAGO INGENIERIA S.L.
*
* Licensed under the EUPL, Version 1.1 only (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/

package com.andago.contentProviders;


import java.util.HashMap;

import com.andago.contentProviders.Devices.DevicesData;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class DevicesDataProvider extends ContentProvider{
	
	private SQLiteDatabase mDB;
	private static final String TAG = "DevicesDataProvider";
	private static final String DATABASE_NAME = "devices.db";
	private static final String DEVICES_TABLE_NAME = "devicesdata";
	private static final int DATABASE_VERSION = 1;
	private static final int DEVICESDATA = 1;
	private static final int DEVICE_ID = 2;
	
	private static final UriMatcher URL_MATCHER;
	private static HashMap<String, String> DEVICES_LIST_PROJECTION_MAP;
	
	private static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name,	CursorFactory factory, int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			
			db.execSQL("CREATE TABLE "+DEVICES_TABLE_NAME+" ("+
					DevicesData._ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
					DevicesData.DEVICE_NAME + " TEXT, "+
					DevicesData.ADDRESS_NAME + " TEXT, "+
					DevicesData.VAR_NAME + " TEXT, "+
					DevicesData.DATE + " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS devicesdata");
			onCreate(db);
		}


	}

	
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		try {
			DatabaseHelper dbHelper = new DatabaseHelper(getContext(),DevicesDataProvider.DATABASE_NAME, null, DevicesDataProvider.DATABASE_VERSION);
			mDB = dbHelper.getWritableDatabase();
			return (mDB == null) ? false : true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}	
	
	
	@Override
	public int delete(Uri url, String where, String[] whereArgs) {
		// TODO Auto-generated method stub
		int count;
		switch (URL_MATCHER.match(url)) {
		case DEVICESDATA:
			count = mDB.delete(DEVICES_TABLE_NAME, where, whereArgs);
			break;
		case DEVICE_ID:
			String segment = url.getPathSegments().get(1);
			count = mDB.delete(DEVICES_TABLE_NAME,"_id="+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where+ ')' : ""), whereArgs);
			break;
		
		default:
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (URL_MATCHER.match(uri)) {
		case DEVICESDATA:
			return "vnd.android.cursor.dir/vnd.andago.devicesdata";
		case DEVICE_ID:
			return "vnd.android.cursor.item/vnd.andago.devicesdata";	
		default:
			throw new IllegalArgumentException("Unknown URL " + uri);
		}
	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		// TODO Auto-generated method stub
		long rowID;
		ContentValues values;
		
		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}

		if (URL_MATCHER.match(url) != DEVICESDATA) {
			throw new IllegalArgumentException("Unknown URL " + url);
		}

		Resources r = Resources.getSystem();


		if ((URL_MATCHER.match(url) == DEVICESDATA)) {

			if (values.containsKey(Devices.DevicesData.VAR_NAME) == false) {
				values.put(Devices.DevicesData.VAR_NAME, r
						.getString(android.R.string.untitled));
			}

			if (values.containsKey(Devices.DevicesData.DEVICE_NAME) == false) {
				values.put(Devices.DevicesData.DEVICE_NAME, r
						.getString(android.R.string.untitled));
			}
			if (values.containsKey(Devices.DevicesData.ADDRESS_NAME) == false) {
				values.put(Devices.DevicesData.ADDRESS_NAME, r
						.getString(android.R.string.untitled));
			}			
			if (values.containsKey(Devices.DevicesData.DATE) == false) {
				values.put(Devices.DevicesData.DATE, r
						.getString(android.R.string.untitled));
			}

			rowID = mDB.insert(DEVICES_TABLE_NAME, null, values);
			if (rowID > 0) {
				Uri uri = ContentUris.withAppendedId(Devices.DevicesData.CONTENT_URI, rowID);
				getContext().getContentResolver().notifyChange(uri, null);
				return uri;
			}
		}		

		throw new SQLException("Failed to insert row into " + url);
	}

	

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sort) {
		// TODO Auto-generated method stub
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(DEVICES_TABLE_NAME);

		switch (URL_MATCHER.match(uri)) {

		case DEVICESDATA:	
			qb.setTables("devicesdata");
			qb.setProjectionMap(DEVICES_LIST_PROJECTION_MAP);
			break;
		case DEVICE_ID:
			qb.appendWhere("_id=" + uri.getPathSegments().get(1));
			break;			
		default:
			throw new IllegalArgumentException("Unknown URL " + uri);
		}

		// If no sort order is specified use the default 
		String orderBy;
		if (TextUtils.isEmpty(sort)) {
			orderBy = Devices.DevicesData.DEFAULT_SORT_ORDER;
		} else {
			orderBy = sort;
		}

		Cursor c = qb.query(mDB, projection, selection, selectionArgs, null,null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;		
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		// TODO Auto-generated method stub
	    int count;
        switch (URL_MATCHER.match(uri)) {
        case DEVICESDATA:
            count = mDB.update(DEVICES_TABLE_NAME, values, where, whereArgs);
            break;

        case DEVICE_ID:
            String segment = uri.getPathSegments().get(1);
            count = mDB.update(DEVICES_TABLE_NAME, values, DevicesData._ID+ "=" + segment
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;

	}

	
	static {
		URL_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
		URL_MATCHER.addURI("com.andago.contentProviders.Devices","DevicesData", DEVICESDATA);
		URL_MATCHER.addURI("com.andago.contentProviders.Devices","DevicesData/#", DEVICE_ID);

		DEVICES_LIST_PROJECTION_MAP = new HashMap<String, String>();
		DEVICES_LIST_PROJECTION_MAP.put(Devices.DevicesData._ID, "_id");
		DEVICES_LIST_PROJECTION_MAP.put(Devices.DevicesData.VAR_NAME, "variableName");
		DEVICES_LIST_PROJECTION_MAP.put(Devices.DevicesData.DEVICE_NAME, "deviceName");
		DEVICES_LIST_PROJECTION_MAP.put(Devices.DevicesData.ADDRESS_NAME, "addressName");
		DEVICES_LIST_PROJECTION_MAP.put(Devices.DevicesData.DATE, "Date");
			
	}
}
